package com.spider.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupUtils2 {
	
	private List<List<String>> optionImgUrlList;
	private List<String> imgUrlList;
	private List<String> optionList;

	// private Map<String,String> contentMap = new HashMap();

	private Matcher match;
	private Pattern pattern;

	public static void main(String[] args) {
		new JsoupUtils2().resolveOption(new File("./text"));
	}

	private List<String> processOptionImg(String cont) {
		List<String> imgUrlList = new ArrayList();
		String regex = "[a-zA-z]+://[^\\s]*png";
		pattern = pattern.compile(regex);
		match = pattern.matcher(cont);
		while (match.find()) {
			imgUrlList.add(match.group());
		}
		if(!match.find()){
			imgUrlList.add("");
		}
		return imgUrlList;
	}

	private List<List> optionReso(Document doc) {
		optionImgUrlList = new ArrayList();
		optionList = new ArrayList();
		Elements data_id = doc.select("div[id*=optionHtmlList] script");
		for (Element element : data_id) {
			optionList.add(element.html());
		}
		List<String> contentList = new ArrayList<String>();
		for (String str : optionList) {
			String s = str.substring("converToArray.push({".length()).trim()
					.substring("id:'optionHtmlList-62241537',".length()).trim().substring("html:\"[".length());
			// .substring("html::[{::optionHtml:::::".length()).trim());
			// System.out.println(s.replaceAll("\\{.{2}optionHtml.{5}", ""));
			String[] sp = s.replaceAll("\\{.{2}optionHtml.{5}", "").split("\\\\\"},");
			for (String s1 : sp) {
				String s2 = s1.replaceAll("\\\\\"}]\"", "").replaceAll("}.;", "").trim();
				imgUrlList = this.processOptionImg(s2);
//				if (imgUrlList.isEmpty()) {
//					optionImgUrlList.add(null);
//				} else {
					optionImgUrlList.add(imgUrlList);
//				}
				contentList.add(s2.replaceAll("&lt;img  border=&#39;0&#39; src=&#39;", "").replaceAll("[a-zA-z]+://[^\\s]*", "<img>"));
			}
		}
		List<List> resultList = new ArrayList();
		resultList.add(contentList);
		resultList.add(optionImgUrlList);	
		return resultList;
	}

	public List<List> resolveOption(File file) {
		Document doc = null;
		try {
			doc = Jsoup.parse(file, "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return this.optionReso(doc);
	}

	public List<List> resolveOption(String htmlContent) {
		String html = htmlContent;
		Document doc = Jsoup.parse(html);
		return this.optionReso(doc);
	}


}
